package com.example.administrator.service;

import android.annotation.TargetApi;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Intent;
import android.icu.util.Calendar;
import android.os.Build;
import android.provider.CalendarContract;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {

    private static MainActivity appRef = null;
    private Button b_call_service, b_exit_service;
    boolean k =false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        appRef = this;

        b_call_service = (Button) findViewById(R.id.button1);
        b_call_service.setOnClickListener(this);
        b_exit_service = (Button) findViewById(R.id.button2);
        b_exit_service.setOnClickListener((View.OnClickListener) this);
    }

    public static MainActivity getApp()
    {
        return appRef;
    }

    public void btEvent(String data)
    {
        setTitle(data);
    }

    @TargetApi(Build.VERSION_CODES.N)
    public void  onClick(View arg0){
        if(arg0 == b_call_service){
            setTitle("Waiting... Alarm = 5");
            Intent intent = new Intent(this,AlarmReceiver.class);
            PendingIntent pendingIntent = PendingIntent.getBroadcast(
                    MainActivity.this, 0, intent, 0);

            Calendar calendar = Calendar.getInstance();
            calendar.setTimeInMillis(System.currentTimeMillis());
            calendar.add(Calendar.SECOND, 3);

            AlarmManager am =(AlarmManager)getSystemService(ALARM_SERVICE);
            am.set(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), pendingIntent);
        }

        if(arg0 ==b_exit_service){
            Intent intent = new Intent(this, AlarmReceiver.class);
            PendingIntent pendingIntent = PendingIntent.getBroadcast(
                    this, 0 , intent, 0);
            AlarmManager am = (AlarmManager) getSystemService(ALARM_SERVICE);
            am.cancel(pendingIntent);
            finish();
        }
    }

}
